'use strict';
const Router = require('koa-router');
const router = new Router({prefix:'/viewdata'});
const debug = require('debug');
const es = require('../elasticsearch');
const log = debug('viewdata:router');
const url = require('url');
const saveIp = require('../config/save-ip');
const DomainIp = require('../domain-ip');

const { getLog, getPUData } = require('../logServer/controllers/Log')

const domainIps = saveIp.map(function (val) {
  return new DomainIp(val);
})

function zeroFill(num) {
  return num > 9 ? num : ('0' + num)
}

function dateFormat(timestamp) {
  const date = new Date(timestamp);
  date.setHours(date.getHours()-8);
  return date.getFullYear() + '-'
    + zeroFill(date.getMonth() + 1) + '-'
    + zeroFill(date.getDate()) + 'T'
    + zeroFill(date.getHours()) + ':'
    + zeroFill(date.getMinutes()) + ':'
    + zeroFill(date.getSeconds()) + '.'
    + date.getMilliseconds() + 'Z'
}
router.get('/', (ctx) => {
  // return new Promise(function (resolve, reject) {
  //   db('', 0, function (error, data) {
  //     if (error) return ctx.body = JSON.stringify({
  //       code: '999999',
  //       message: error.message
  //     });

  //     ctx.body = JSON.stringify({
  //       code: '000000',
  //       message: 'success',
  //       data: data
  //     });
  //     resolve();
  //   });
  // })
  ctx.body = 'ok';
});

const matchPhrase = function (key, value) {
  return {
    "match_phrase": { "message": `"${key}":"${value}"` }
  }
}

const range = function (start, end) {
  return {
    "range": {
      "@timestamp": {
        "gte": start ? dateFormat(start) : "",
        "lte": end ? dateFormat(end) : "",
        "format": "strict_date_optional_time"
      }
    }
  }
}

router.post('/', async (ctx) => {
  const referer = ctx.headers.referer;
  const { body } = ctx.request;
  return new Promise(function (resolve, reject) {
    const myUrl = url.parse(referer)
    const result = domainIps.findIndex(function (domainIp) {
      return domainIp.isIn(myUrl.hostname)
    })
    if (result === -1) {
      ctx.body = 'ok';
      return resolve();
    }
    const arr = [];
    if (body.moonid) arr.push(matchPhrase("moonid", body.moonid));
    if (body.env) arr.push(matchPhrase("env", body.env));
    if (body.startDate || body.endDate) arr.push(range(body.startDate, body.endDate));
    if (body.wheresql) arr.push({
      "match_phrase": { "message": `${body.wheresql}` }
    });
    es(arr, function (error, res) {
 //  log('res', res);
      if (error) {
        ctx.body = JSON.stringify({
          code: '999999',
          message: error.message
        });
        return resolve();
      }
      let list = [];
      try {
        list = JSON.parse(res.body).hits.hits.map(v => v._source.message)
      } catch (e) {
        ctx.body = JSON.stringify({
          code: '999999',
          message: e.message
        });
        return resolve();
      }
      ctx.body = JSON.stringify({
        code: '000000',
        message: 'success',
        data: list
      });
      resolve();
    })
  })
});

router.post('/getLog', getLog)
router.get('/getLog', ctx => {
  ctx.body = 'ok'
})

router.post('/getPUData', getPUData)
router.get('/getPUData', ctx => {
  ctx.body = 'ok'
})

module.exports = router;

// let wheresql = body.wheresql || ' 1 = 1';
// if(body.startDate) wheresql += ` and create_time >= '${dateFormat(body.startDate)}'`
// if(body.moonid) wheresql += ` and remark like '%"moonid":"${body.moonid}"%'`
// if(body.env) wheresql += ` and env = '${body.env}'`
// if(body.endDate) wheresql += ` and create_time <= '${dateFormat(body.endDate)}'`

// db(wheresql, body.page, function (error, data) {
//   if (error) ctx.body = JSON.stringify({
//     code: '999999',
//     message: error.message
//   });
//   else ctx.body = JSON.stringify({
//     code: '000000',
//     message: 'success',
//     data: data
//   });
//   resolve();
// });